package com.ruoyi.web.controller.vantController.shopController;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.AliyunSmsUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.system.domain.supe.PlatformCoupon;
import com.ruoyi.system.domain.vo.ApiBuildingVo;
import com.ruoyi.system.domain.zhuangxiumain.shopMain.*;
import com.ruoyi.system.service.vantservice.shopservice.ApiProductInfoService;
import com.ruoyi.system.service.zhaungxiuservice.shopService.ProductDetailsImgService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.extern.log4j.Log4j2;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.HttpsURLConnection;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

@Api(value = "前端商品信息接口", tags = {"前端商品信息接口"})
@RestController
@RequestMapping("/api/shop/product")
@CrossOrigin
@Log4j2
public class ApiProductInfoController extends BaseController {

    @Autowired(required = false)
    private ApiProductInfoService apiProductInfoService;
    @Autowired
    private ProductDetailsImgService productDetailsImgService;
    @Value("${ruoyi.telphone}")
    private String telPhone;

    @Autowired(required = false)
    private HttpServletRequest request;

    // 查询首页商品
    @GetMapping("/findAllListHome")
    public TableDataInfo findAllList(ProductInfo productInfo){
        List<ProductInfo> allList = apiProductInfoService.findAllList(productInfo);
        return getDataTable(allList);
    }

    @GetMapping("/findAllAdder/{address}")
    public TableDataInfo findAllAdder(@PathVariable("address") String address){
        List<ProductInfo> allList = apiProductInfoService.findAllAdder(address);
        return getDataTable(allList);
    }

    @PostMapping("/ipAddress")
    public AjaxResult ipAddress() throws Exception{
        String key = "2c945ec8d99c3ce7aacdbbf9b60a1bbd";
        String url_head = "https://restapi.amap.com/v5/ip?output=json&key=" ;
        String ipAddr = IpUtils.getIpAddr(request);
        String Url_str = url_head + key + "&ip=" + ipAddr + "&type=4";

        URL url = new URL(Url_str);
        HttpsURLConnection urlcon = (HttpsURLConnection) url.openConnection();
        urlcon.connect();
        BufferedReader br = new BufferedReader(
                new InputStreamReader(urlcon.getInputStream(),"utf-8"));
        StringBuffer sb = new StringBuffer();
        String content = null ;
        while((content=br.readLine())!=null) {
            sb.append(content);
        }
        JSONObject jsonObject = JSONObject.fromObject(sb.toString());
        return AjaxResult.success(jsonObject);
    }

    @GetMapping("/apilist")
    public TableDataInfo list(ProductInfo productInfo) throws Exception
    {
        List<ProductInfo> list = apiProductInfoService.findAllList(productInfo);
        return getDataTable(list);
    }

    @PostMapping("/findConstructionList")
    public TableDataInfo findConstructionList(@RequestBody(required = false) ApiBuildingVo apiBuildingVo)
    {
        List<ApiBuildingVo> list = apiProductInfoService.findConstructionList(apiBuildingVo);
        return getDataTable(list);
    }

    //修改
    @GetMapping(value = "/{productId}")
    public AjaxResult getInfo(@PathVariable("productId") Integer productId)
    {
        return AjaxResult.success(apiProductInfoService.selectProductInfoById(productId));
    }

    /**
     * 查询所有商品类别信息
     * @return
     */
    @ApiOperation(value = "根据品类类别查询商品信息")
    @GetMapping("/getCateGoryList/{categoryType}")
    public AjaxResult getCateGoryList(@PathVariable(value = "categoryType", required = false) String categoryType)
    {
        return AjaxResult.success(apiProductInfoService.selectProductCategories(categoryType));
    }

    /**
     * 根据商品类别ID查询商品列表
     * @param cateGoryId
     * @return
     */
    @ApiOperation(value = "查询商品类别下的商品信息")
    @GetMapping("/getProductByCateGory/{cateGoryId}")
    public AjaxResult getProductByCateGory(@PathVariable(value = "cateGoryId", required = false) Long cateGoryId)
    {
        return AjaxResult.success(apiProductInfoService.selectProductByCateGory(cateGoryId));
    }

    @PostMapping("/selectProductByCateGoryOne")
    public AjaxResult selectProductByCateGoryOne(@RequestBody ProductInfo productInfo)
    {
        return AjaxResult.success(apiProductInfoService.selectProductByCateGoryOne(productInfo));
    }




    /**
     * 所有商品类别ID查询商品列表
     * @param
     * @return
     */
    @ApiOperation(value = "查询商品类别下的商品信息")
    @GetMapping("/selectProductByCateGoryList")
    public AjaxResult selectProductByCateGoryList()
    {
        return AjaxResult.success(apiProductInfoService.selectProductByCateGoryList());
    }


    /**
     * 查询二级类别
     * @param cateGoryId
     * @return
     */
    @ApiOperation(value = "查询二级类别")
    @GetMapping("/getSecondCateGory/{cateGoryId}")
    public AjaxResult getSecondCateGory(@PathVariable(value = "cateGoryId", required = false) Long cateGoryId)
    {
        return AjaxResult.success(apiProductInfoService.selectSecondCategories(cateGoryId));
    }


    /**
     * 全部查询二级类别
     * @param cateGoryId
     * @return
     */
    @ApiOperation(value = "查询二级类别")
    @GetMapping("/selectSecondAll")
    public AjaxResult selectSecondAll(Long cateGoryId)
    {
        return AjaxResult.success(apiProductInfoService.selectSecondAll());
    }


    /**
     * 根据商品类别ID查询商品列表
     * @param cateGoryId
     * @return
     */
    @ApiOperation(value = "查询商品类别下的商品信息")
    @GetMapping("/selectProductByCateGory/{cateGoryId}")
    public AjaxResult selectProductByCateGory(@PathVariable(value = "cateGoryId", required = false) Long cateGoryId)
    {
        return AjaxResult.success(apiProductInfoService.getProductByCateGory(cateGoryId));
    }

    @GetMapping("/CateGoryName/{categoryName}")
    public AjaxResult CateGoryName(@PathVariable(value = "categoryName", required = false) String categoryName)
    {
        return AjaxResult.success(apiProductInfoService.CateGoryName(categoryName));
    }

    /**
     * 根据品类类别查询商品列表
     * @param categoryType
     * @return
     */
    @ApiOperation(value = "根据品类类别查询商品列表")
    @GetMapping("/selectProductByCateGoryType/{categoryType}")
    public AjaxResult selectProductByCateGoryType(@PathVariable(value = "categoryType", required = false) String categoryType)
    {
        return AjaxResult.success(apiProductInfoService.selectProductByCateGoryType(categoryType));
    }


    @GetMapping("/selectProductByCateGoryTypeOne/{address}")
    public AjaxResult selectProductByCateGoryTypeOne(@PathVariable(value = "address", required = false) String address)
    {
        return AjaxResult.success(apiProductInfoService.selectProductByCateGoryTypeOne(address));
    }

 @GetMapping("/selectProductByCateGoryTypeTwo/{address}")
    public AjaxResult selectProductByCateGoryTypeTwo(@PathVariable(value = "address", required = false) String address)
    {
        return AjaxResult.success(apiProductInfoService.selectProductByCateGoryTypeTwo(address));
    }



    /**
     * 根据商品ID查询商品信息
     * @return
     */
    @ApiOperation(value = "根据商品ID查询商品信息")
    @GetMapping("/getProductById/{productId}")
    public AjaxResult getProductById(@PathVariable(value = "productId", required = false) Long productId){
        ProductInfo product = apiProductInfoService.getProductById(productId);
        return AjaxResult.success(product);
    }

    @GetMapping("/xiaoliang/{productId}")
    public AjaxResult xiaoliang(@PathVariable(value = "productId", required = false) Long productId){
        return AjaxResult.success(apiProductInfoService.xiaoliang(productId));
    }

    /**
     * 根据供应商ID查询供应商信息
     * @param supplierId
     * @return
     */
    @ApiOperation(value = "根据供应商ID查询供应商信息")
    @GetMapping("/getSupplierById/{supplierId}")
    public AjaxResult getSupplierById(@PathVariable(value = "supplierId", required = false) Long supplierId){
        return AjaxResult.success(apiProductInfoService.getSupplierById(supplierId));
    }

    /**
     * 根据供应商ID查询商品信息
     * @param supplierId
     * @return
     */
    @ApiOperation(value = "根据供应商ID查询商品信息")
    @GetMapping("/selectProductBySupplierId/{supplierId}")
    public AjaxResult selectProductBySupplierId(@PathVariable(value = "supplierId", required = false) Long supplierId){
        return AjaxResult.success(apiProductInfoService.selectProductBySupplierId(supplierId));
    }


    @ApiOperation(value = "根据商品Id查询产品详情")
    @GetMapping("/listDetailsImg/{productId}")
    public AjaxResult listDetailsImg(@PathVariable(value = "productId", required = false) Long productId)
    {
        List list = productDetailsImgService.getProductInfoPicById(productId);
        return AjaxResult.success(productDetailsImgService.getProductInfoPicById(productId));
    }
    /**
     *根据商品名称查询商品信息
     * @param productName
     * @return
     */
    @ApiOperation(value = "根据商品名称查询商品信息")
    @GetMapping("/selectProductByName/{productName}")
    public AjaxResult selectProductByName(@PathVariable(value = "productName", required = false) String productName){
        return AjaxResult.success(apiProductInfoService.selectProductByName(productName));
    }




    @PostMapping("/uploadImg")
    public Map uploadImg(@RequestParam(value = "file",required = false) MultipartFile[] file, ProductPicInfo productPicInfp){
        productPicInfp.setModifiedTime(new Date());
        return apiProductInfoService.uploadImg(file,productPicInfp);
    }


    @ApiOperation(value = "根据商品Id查询商品的规格信息")
    @GetMapping("/selectProductLableByProId/{productId}")
    public AjaxResult selectProductLableByProId(@PathVariable(value = "productId", required = false) Long productId){
        return AjaxResult.success(apiProductInfoService.selectProductLableByProId(productId));
    }

    @ApiOperation(value = "根据规格Id查询商品的规格信息")
    @GetMapping("/selectProductLableByLableId/{productLableId}")
    public AjaxResult selectProductLableByLableId(@PathVariable(value = "productLableId", required = false) Long productLableId){
        return AjaxResult.success(apiProductInfoService.selectProductLableByLableId(productLableId));
    }


    @ApiOperation(value = "查询商家优惠券列表")
    @GetMapping("/selectSupplierCoupon/{supplierId}")
    public AjaxResult selectSupplierCoupon(@PathVariable(value = "supplierId", required = false) Long supplierId){
        AjaxResult ajaxResult = AjaxResult.success();
        try {
            ajaxResult.put("preferentialCard",apiProductInfoService.selectSupplierCoupon(supplierId));
            ajaxResult.put("platformCoupon",apiProductInfoService.selectSupplierPlatformCoupon(supplierId));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            return ajaxResult;
        }
    }

    /**
     * 根据商品的id查询规格图片
     * @param productId
     * @return
     */
    @PostMapping("/selectPpiUrl/{productId}")
    public AjaxResult PpiUrl(@PathVariable("productId") Integer productId){
        return AjaxResult.success(apiProductInfoService.selectPpiUrl(productId));
    }

    @ApiOperation(value = "添加购物车")
    @RequestMapping(value = "/saveShopping",method = RequestMethod.GET)
    public AjaxResult saveShopping(){

        return null;

    }

    /**
     * 上传营业执照
     * @param file
     * @return
     */
    @ApiOperation(value = "上传营业执照")
    @PostMapping("/uploadLicense")
    public AjaxResult uploadLicense(@RequestParam("licenseFile") MultipartFile file) throws IOException {
        if (!file.isEmpty())
        {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getLicensePath(), file);
            return AjaxResult.success("上传成功",avatar);
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 上传营业执照
     * @param file
     * @return
     */
    @ApiOperation(value = "上传资质证书")
    @PostMapping("/uploadCertificate")
    public AjaxResult uploadCertificate(@RequestParam("certificateFile") MultipartFile file) throws IOException {
        if (!file.isEmpty())
        {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getCertificatePath(), file);
            return AjaxResult.success("上传成功",avatar);
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 上传企业logo
     * @param file
     * @return
     */
    @ApiOperation(value = "上传企业logo")
    @PostMapping("/uploadSupplierPic")
    public AjaxResult uploadSupplierPic(@RequestParam("supplierPicFile") MultipartFile file) throws IOException {
        if (!file.isEmpty())
        {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getCertificatePath(), file);
            return AjaxResult.success("上传成功",avatar);
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 申请入驻
     * @param supplierInfo
     * @return
     */
    @ApiOperation(value = "申请入驻")
    @PostMapping("/installSupplier")
    public AjaxResult installSupplier(@RequestBody SupplierInfo supplierInfo){
        int count = apiProductInfoService.checkSupplierPhone(supplierInfo);
        if(count>0){
            return AjaxResult.error(201,"店铺联系人手机已存在");
        }else{
            int counts = apiProductInfoService.installSupplier(supplierInfo);
            if ( counts > 0) {
                AliyunSmsUtils smsUtils = new AliyunSmsUtils();
                try {
                    //发送短信
                    SendSmsResponse response = smsUtils.sendSms(telPhone, null);
                } catch (ClientException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return AjaxResult.success(counts);
        }
    }
}
